package com.hyacinth.forumbite.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hyacinth.forumbite.common.AppResult;
import com.hyacinth.forumbite.common.ResultCode;
import com.hyacinth.forumbite.dao.ArticleMapper;
import com.hyacinth.forumbite.dao.UserMapper;
import com.hyacinth.forumbite.exception.ApplicationException;
import com.hyacinth.forumbite.model.Article;
import com.hyacinth.forumbite.model.Board;
import com.hyacinth.forumbite.model.Like;
import com.hyacinth.forumbite.model.User;
import com.hyacinth.forumbite.service.ArticleService;
import com.hyacinth.forumbite.service.BoardService;
import com.hyacinth.forumbite.service.UserService;
import com.hyacinth.forumbite.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: Yun
 * @Date: 2025/5/22
 */
@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private UserService userService;

    @Resource
    private BoardService boardService;
    private UserMapper userMapper;

    @Override
    public void create(Article article) {
        // 发布帖子   1.帖子表中新增帖子数据 2.用户发帖数量+1 3.板块帖子数量+1
        if (article == null || article.getBoardId() == null || article.getUserId() == null
                || StringUtil.isEmpty(article.getTitle()) || StringUtil.isEmpty(article.getContent())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Date date = new Date();
        article.setCreateTime(date)
                .setUpdateTime(date)
                .setLikeCount(0) // 点赞数量
                .setReplyCount(0) // 回复数量
                .setVisitCount(0) //访问数量
                .setDeleteState((byte) 0)
                .setState((byte) 0);
        int inserted = articleMapper.insertSelective(article);
        if (inserted < 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        User user = userService.selectById(article.getUserId());
        if (user == null) {
            log.warn("查询不到指定用户: userId" + article.getUserId() + ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        userService.addOneArticleCountById(article.getUserId());

        Board board = boardService.selectById(article.getBoardId());
        if (board == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        boardService.addOneArticleCountById(article.getBoardId());

        log.info(ResultCode.SUCCESS.toString());

    }

    @Override
    public List<Article> selectAll() {
        return articleMapper.selectAll();
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        if (boardId == null || boardId < 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 检查板块是否存在
        Board board = boardService.selectById(boardId);
        if (board == null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        if (articles == null) {
            return new ArrayList<>();
        }
        return articles;
    }

    @Override
    public Article selectDetailsById(Long id) {
        if (id == null || id < 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询帖子
        Article article = articleMapper.selectById(id);
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 帖子访问数+1
        article.setVisitCount(article.getVisitCount() + 1);
        Article updateArticle = new Article()
                .setId(article.getId())
                .setVisitCount(article.getVisitCount());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        if (id == null || id < 1 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = new Article()
                .setId(id)
                .setTitle(title)
                .setContent(content);
        int row = articleMapper.updateByPrimaryKeySelective(article);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED.toString()));
        }

    }

    @Override
    public Article selectByPrimaryKey(Long id) {
        if (id == null || id < 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addLikeCount(Long id) {
        if (id == null || id < 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_STATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_STATE));
        }
        Article updateArticle = new Article()
                .setId(id)
                .setLikeCount(article.getLikeCount() + 1)
                .setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public boolean like(Long userId, Long articleId) {
        if (userId == null || articleId == null || userId < 1 || articleId < 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(articleId);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_STATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_STATE));
        }
        // 1. 先查询有否有点赞数据 ,没有就插入(点赞), 有就修改
        Like like = articleMapper.selectByUserIdAndArticleId(userId, articleId);
        if (like == null) {
            articleMapper.insertLike(userId, articleId, 1);
            Article updateArticle = new Article()
                    .setId(articleId)
                    .setLikeCount(article.getLikeCount() + 1)
                    .setUpdateTime(new Date());
            int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
            if (row != 1) {
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
            }
            return true;
        } else {
            Article updateArticle = new Article()
                    .setId(articleId)
                    .setUpdateTime(new Date());
            if (like.getIsLiked() == 1) {
                like.setIsLiked(0);
                updateArticle.setLikeCount(article.getLikeCount() - 1);
            } else {
                like.setIsLiked(1);
                updateArticle.setLikeCount(article.getLikeCount() + 1);
            }
            articleMapper.updateLike(userId, articleId, like.getIsLiked());
            int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
            if (row != 1) {
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
            }
            return like.getIsLiked() == 1;
        }
    }

    @Override
    public void deleteById(Long id) {
        if (id == null || id < 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        userService.subOneArticleCountById(article.getUserId());
        boardService.subOneArticleCountById(article.getBoardId());
        Article updateArticle = new Article()
                .setId(id)
                .setDeleteState((byte) 1)
                .setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void addOneReplyCountById(Long id) {
        if (id == null || id < 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_STATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_STATE));
        }
        Article updateArticle = new Article()
                .setId(id)
                .setReplyCount(article.getReplyCount() + 1)
                .setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public List<Article> getArticleListByUserId(Long id) {
        if (id == null || id < 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userService.selectById(id);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        List<Article> articleList = articleMapper.getArticleListByUserId(id);
        if (articleList == null) {
            return new ArrayList<>();
        }
        return articleList;
    }

    @Override
    public PageInfo<Article> likeArticles(Long userId, int pageNum, int pageSize) {
        PageHelper.startPage(1, 10);
        List<Article> likeArticleListByUserId = articleMapper.getLikeArticleListByUserId(userId);
        PageInfo<Article> articlePageInfo = new PageInfo<>(likeArticleListByUserId);
        return articlePageInfo;
    }
}
